package com.proton.carepatchtemp.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.database.table.Profile;
import com.proton.carepatchtemp.utils.FileUtils;
import com.proton.carepatchtemp.utils.NetUtils;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.PrfCenter;
import com.proton.carepatchtemp.utils.net.oss.OSSUtils;
import com.sdsmdg.tastytoast.TastyToast;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.Calendar;

import cn.qqtheme.framework.picker.DatePicker;

public class AddProfileActivity extends BaseActivity {
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 4;
    protected Uri tempUri;
    private String ossAvatorUri = "";
    private DatePicker mDatePicker;
    private boolean isManChecked = true;
    private Profile mProfile;
    private ProgressDialog mProgressDialog;
    private ImageButton mBtnBack;
    private TextView mTvAddProfile;
    private SimpleDraweeView mSdvAddAvator;
    private EditText mEtName;
    private TextView mTvMan;
    private TextView mTvWoman;
    private TextView mTvBirthday;
    /**
     * 档案设置
     */
    private TextView mTvAddProfileTitle;
    private File mCameraFile = new File(FileUtils.getDataCache(), "image.jpg");
    protected Uri cropUri = Uri.fromFile(new File(FileUtils.avatar));

    @Override
    public void dealEvent(MainEvent event) {
        switch (event.getId()) {
            case Codes.NET_PRF_ADD:
                if (event.isSuccess()) {
                    TastyUtils.makeTextShort(R.string.string_add_profile_success, TastyToast.SUCCESS);
                    mProgressDialog.dismiss();
                    finish();
                } else {
                    mProgressDialog.dismiss();
                    TastyUtils.makeTextShort(
                            event.getMsg(), TastyToast.ERROR);
                }
                break;
            case Codes.NET_PRF_EDIT:
                if (event.isSuccess()) {
                    TastyUtils.makeTextShort(R.string.string_modify_profile_success, TastyToast.SUCCESS);
                    mProgressDialog.dismiss();
                    finish();
                } else {
                    mProgressDialog.dismiss();
                    TastyUtils.makeTextShort(
                            event.getMsg(), TastyToast.ERROR);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_profile);
        initView();
        if (null != getIntent().getExtras()) {
            mTvAddProfileTitle.setText(R.string.edit_profile);
            mProfile = (Profile) getIntent().getExtras().get(Extras.PRF_EDIT);

            if (mProfile != null) {
                ossAvatorUri = mProfile.getAvatar();
                mSdvAddAvator.setImageURI(mProfile.getAvatar());
                if (!TextUtils.isEmpty(mProfile.getBirthday())) {
                    String[] s = mProfile.getBirthday().split("-");
                    StringBuilder str = new StringBuilder();
                    str.append(s[0]).append("-").append(s[1]).append("-").append(s[2]);
                    mTvBirthday.setText(str);
                }


                if (1 == mProfile.getGender()) {
                    mTvMan.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.checked, 0);
                    mTvWoman.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.unchecked, 0);
                    isManChecked = true;
                } else {
                    mTvWoman.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.checked, 0);
                    mTvMan.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.unchecked, 0);
                    isManChecked = false;
                }
                mEtName.setText(mProfile.getRealname());
            } else {
                mProfile = new Profile();
            }
        } else {
            mProfile = new Profile();
        }


        //  出生年月选择器
        mDatePicker = new DatePicker(this, DatePicker.YEAR_MONTH_DAY);
        mDatePicker.setLabel(getString(R.string.string_year), getString(R.string.string_month), getString(R.string.string_day));
        mDatePicker.setRangeStart(1900, 1, 1);//开始范围
        mDatePicker.setRangeEnd(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH) + 1, Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + 1);
        //结束范围
        mDatePicker.setSelectedItem(2000, 1, 1);
        mDatePicker.setTitleText(R.string.birthday);

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setCancelable(false);

        setListener();
        onInitSex();
    }

    @Override
    public void setListener() {

        mBtnBack.setOnClickListener(view -> {
            finish();
        });

        mTvAddProfile.setOnClickListener(view -> {
            if (NetUtils.noNet()) {
                TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
                return;
            }
            mProfile.setAvatar(ossAvatorUri);
            if (TextUtils.isEmpty(mEtName.getText())) {
                TastyUtils.makeTextShort(R.string.profile_name, TastyToast.DEFAULT);
                return;
            } else {
                mProfile.setRealname(mEtName.getText().toString());
                mProfile.setTitle(mEtName.getText().toString());
            }

            if (isManChecked) {
                mProfile.setGender(1);
            } else {
                mProfile.setGender(2);
            }

            if (TextUtils.isEmpty(mTvBirthday.getText())) {
                TastyUtils.makeTextShort(R.string.select_birthday, TastyToast.DEFAULT);
                return;
            } else {
                String str = mTvBirthday.getText().toString();
                String[] strs = str.split("-");
                String birthday = new StringBuilder().append(strs[0]).append("-").append(strs[1]).append("-").append(strs[2]).toString();
                mProfile.setBirthday(birthday);
            }

            if (null != mProfile.getId()) {
                PrfCenter.edit(mProfile);
            } else {
                PrfCenter.add(mProfile);
            }
            mProgressDialog.setMessage(getString(R.string.wait));
        });

        mSdvAddAvator.setOnClickListener(view -> findIamgeUrl());

        mTvBirthday.setOnClickListener(view -> {
            mDatePicker.show();
        });

        //生日设置监听器
        mDatePicker.setOnDatePickListener((DatePicker.OnYearMonthDayPickListener) (year, month, day) -> {
            mTvBirthday.setText(year + "-" + month + "-" + day);
        });


        mTvMan.setOnClickListener(view -> {
            if (isManChecked) {
                mTvMan.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.checked, 0);
                mTvWoman.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.unchecked, 0);
            } else {
                mTvMan.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.checked, 0);
                mTvWoman.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.unchecked, 0);
                isManChecked = !isManChecked;
            }

        });


        mTvWoman.setOnClickListener(view -> {
            if (isManChecked) {
                mTvWoman.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.checked, 0);
                mTvMan.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.unchecked, 0);
                isManChecked = !isManChecked;
            } else {
                mTvWoman.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.checked, 0);
                mTvMan.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.unchecked, 0);
            }
        });
    }

    public void onInitSex() {
        if (isManChecked) {
            mTvMan.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.checked, 0);
        }
    }

    public void findIamgeUrl() {
        if (NetUtils.noNet()) {
            TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
            return;
        }
        showChoosePicDialog();
    }


    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    /**
     * android4.4以后返回的URI只有图片编号
     * 获取图片真实路径
     */
    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = this.getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    private void initView() {
        mBtnBack = findViewById(R.id.btn_back);
        mTvAddProfile = findViewById(R.id.tv_add_profile);
        mSdvAddAvator = findViewById(R.id.sdv_add_avator);
        mEtName = findViewById(R.id.et_name);
        mTvMan = findViewById(R.id.tv_man);
        mTvWoman = findViewById(R.id.tv_woman);
        mTvBirthday = findViewById(R.id.tv_birthday);
        mTvAddProfileTitle = findViewById(R.id.tv_add_profile_title);
    }

    /**
     * 显示修改头像的对话框
     */
    protected void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.string_set_avatar);
        String[] items = {getString(R.string.string_select_photo), getString(R.string.string_take_photo)};
        builder.setNegativeButton(getString(R.string.string_cancel), null);
        builder.setItems(items, (dialog, which) -> {
            switch (which) {
                case CHOOSE_PICTURE: // 选择本地照片
                    openGallery();
                    break;
                case TAKE_PICTURE: // 拍照
                    openCamera();
                    break;
            }
        });
        builder.create().show();
    }

    private void openGallery() {
        Intent openAlbumIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
    }

    private void openCamera() {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tempUri = FileProvider.getUriForFile(
                    this,
                    getPackageName() + ".FileProvider",
                    mCameraFile);
        } else {
            tempUri = Uri.fromFile(mCameraFile);
        }
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        startActivityForResult(takePhotoIntent, TAKE_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case TAKE_PICTURE:
                startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
                break;
            case CHOOSE_PICTURE:
                if (data == null) return;
                startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                break;
            case UCrop.REQUEST_CROP:
                uploadPic();
                break;
        }
    }

    /**
     * 裁剪图片方法实现
     */
    protected void startPhotoZoom(Uri uri) {
        if (uri == null) return;
        UCrop.of(uri, cropUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(300, 300)
                .start(this);
    }

    private void uploadPic() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                mProgressDialog.setMessage(getString(R.string.string_uploading));
                mProgressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                ossAvatorUri = OSSUtils.uploadImg(FileUtils.avatar);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                mSdvAddAvator.setVisibility(View.VISIBLE);
                mSdvAddAvator.setImageURI(ossAvatorUri);
                mProgressDialog.dismiss();
                super.onPostExecute(aVoid);
            }
        }.execute();
    }
}
